{% extends 'sales/base.html' %}
{% load static %}
{% block breadcrumb %}
<nav aria-label="breadcrumb">
  <ol class="breadcrumb">
    <li class="breadcrumb-item"><a href="{% url 'tasks:tasks_list' %}">Tasks</a></li>
    <li class="breadcrumb-item active">{% if task_obj %}Edit{% else %}Create{% endif %}</li>
  </ol>
</nav>
{% endblock %}
{% block content %}
<form id="formid" action='' method="POST" novalidate enctype="multipart/form-data">
  <div class="overview_form_block row marl justify-content-center">
    <div class="col-md-9">
      <div class="card">
        <div class="card-body">
          <div class="card-title text-center">
            {% if task_obj %}EDIT{% else %}CREATE{% endif %} TASK
          </div>
          <div class="row marl">
            <div class="col-md-4">
              <div class="filter_col col-md-12">
                <div class="form-group">
                  <label for="exampleInputEmail1" class="required">Title{% if form.title.field.required %}<span
                      class="error_marker" style="color:red">*</span>{% endif %}</label>
                  {{ form.title }}
                  <span class="error" id="id__title">{{ form.name.errors }}</span>
                </div>
              </div>
              <div class="filter_col col-md-12">
                <div class="form-group">
                  <label for="exampleInputEmail1">Status{% if form.status.field.required %}<span class="error_marker"
                      style="color:red">*</span>{% endif %}</label>
                  {{ form.status }}
                  <span class="error" id="id__status">{{ form.status.errors }}</span>
                </div>
              </div>
              <div class="filter_col col-md-12">
                <div class="form-group">
                  <label for="exampleInputEmail1" class="required">Priority{% if form.priority.field.required %}<span
                      class="error_marker" style="color:red">*</span>{% endif %}</label>
                  {{ form.priority }}
                  <span class="error" id="id__priority">{{ form.priority.errors }}</span>
                </div>
              </div>
            </div>
            <div class="col-md-4">
              <div class="filter_col billing_block col-md-12" style="padding: 0px;">
                <div class="filter_col col-md-12">
                  <div class="form-group ">
                    <label for="exampleInputEmail1" class="required">Due Date{% if form.due_date.field.required %}<span
                        class="error_marker" style="color:red">*</span>{% endif %}</label>
                    <div id="datepicker1" class='input-group date'>
                      {{ form.due_date }}
                      <span class="input-group-addon">
                        <span class="glyphicon glyphicon-calendar"></span>
                      </span>
                    </div>
                    <span class="error" id="id__due_date">{{ form.due_date.errors }}</span>
                  </div>
                </div>
                <input type="hidden" name="from_account" value="{{request.GET.view_account}}">
                <div class="filter_col col-md-12">
                  <div class="form-group ">
                    <label for="exampleInputEmail1" class="required">Account{% if form.account.field.required %}<span
                        class="error_marker" style="color:red">*</span>{% endif %}</label>
                    
                    {{ form.account }}
                    <span class="error" id="id__account">{{ form.account.errors }}</span>
                  </div>
                </div>
                <div class="filter_col col-md-12">
                  <div class="form-group ">
                    <label for="id_contacts" class="required">Contacts{% if form.contacts.field.required %}<span
                        class="error_marker" style="color:red">*</span>{% endif %}</label>
                    {{ form.contacts }}
                    <span class="error" id="id__contacts">{{ form.contacts.errors }}</span>
                  </div>
                </div>
              </div>
            </div>
            <div class="col-md-4">
              <div class="filter_col billing_block col-md-12" style="padding: 0px;">
                {% if request.user.is_superuser or request.user.role == 'ADMIN' %}
                <div class="filter_col col-12">
                  <div class="form-group">
                    <label for="id_sattus">Teams{% if form.teams.field.required %}<span
                        class="error">*</span>{% endif %}</label>
                    <select name="teams" id="id_teams" class="assigned_users form-control" multiple>
                      {% for team in teams %}
                      <option data-users="{{team.get_users}}" value="{{team.id}}" {% if team in task_obj.teams.all %}
                        selected="" {% endif %}>
                        {{team}}</option>
                      {% endfor %}
                    </select>
                    <span class="error" id="id__teams">{{ form.teams.errors }}</span>
                  </div>
                </div>

                <div class="filter_col col-12">
                  <div class="form-group">
                    <label for="id_sattus"><span class="">Users</span></label>
                    <select name="" aria-readonly="true" id="_id_assigned_to" class=" form-control" multiple>
                      {% if task_obj and task_obj.teams.all %}
                      {% for user in users %}
                      {% if user in task_obj.get_team_users %}
                      <option value="{{user.id}}" selected="">{{user.email}}</option>
                      {% else %}
                      <option value="{{user.id}}">{{user.email}}</option>
                      {% endif %}
                      {% endfor %}
                      {% else %}
                      {% for user in users %}
                      <option value="{{user.id}}">{{user.email}}</option>
                      {% endfor %}
                      {% endif %}
                    </select>
                  </div>
                </div>

                {% endif %}
                <div class="filter_col col-md-12">
                  <div class="form-group ">
                    <label for="exampleInputEmail1">Assign To</label>
                    <select id="id_assigned_to" class="assigned_users form-control" name="assigned_to"
                      multiple="multiple">
                      {% for user in users %}
                      <option value="{{user.id}}" {% if user in task_obj.get_assigned_users_not_in_teams %} selected="" {% endif %}>
                        {{user.email}}</option>
                      {% endfor %}
                    </select>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="col-md-12">
            <div class="col-md-12">
              <div class="row marl buttons_row form_btn_row text-center">
                <button class="btn btn-default save" type="submit">Save</button>
                <a href="{% url 'tasks:tasks_list' %}" class="btn btn-default clear" id="create_user_cancel">Cancel</a>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
  </div>
  
</form>
{% endblock %}
{% block js_block %}
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/js/bootstrap-datetimepicker.min.js"></script>
<script type="text/javascript">

  // $(document).ready(function() {
  //   $('.assigned_users').select2();
  // });
  $(document).ready(function () {
    $("#id_contacts").select2();
    {% if request.GET.view_account %}
    $("#id_account option[value=" + '{{request.GET.view_account}}' + "]").attr('selected', true);
    {% endif %}
    $("#id_assigned_to").select2();
    $("#id_teams").select2();
    $('#_id_assigned_to').select2({ disabled: 'readonly' });


    {% if task_obj %}
    $('#id_due_date').datetimepicker({
      'format': 'YYYY-MM-DD',
    })
    {% else %}
    var date = new Date();
    var today = new Date(date.getFullYear(), date.getMonth(), date.getDate());
    $('#id_due_date').datetimepicker({
      'format': 'YYYY-MM-DD',
      minDate: today
    })
    {% endif %}


  });

  $('form#formid').ajaxForm({
    type: 'POST',
    dataType: 'json',
    url: ".",
    data: $('#formid').serialize(),
    success: function (data) {
      if (data.error) {
        $('.error').html('')
        for (var key in data.errors) {
          $('#id__' + key).html("<p>" + data.errors[key][0] + "</p>");
        };
        $('#submit_btn').removeAttr('disabled')
      }
      else {
        window.location = data.success_url;
      }
    }
  });

  function find_dict(dict, id){
    var index = dict.map(function(o) { return o.team; }).indexOf(parseInt(id));
    return dict[index]['users']
  }

  $("#id_teams").change(function (e) {
    var teams = []
    var all_users = []
    var selected_teams = []
    var selected_users = []
    var assigned_users = []
    $.get("{% url 'leads:get_teams_and_users' %}", function(data){
      // console.log(data)
          if(($('#id_teams').val()).length==0){
            $('#id_assigned_to option').each(function () {
            $(this).removeAttr('disabled')
            })
        $('#id_assigned_to').select2().trigger('change');

          }

      teams = data['teams']
      all_users = data['users']
      try {
        var users = []
        $('#id_teams option:selected').each(function () {
          // users.push($(this).attr('data-users'))
          _data = $(this).attr('data-users');
          selected_teams.push($(this).val())
          selected_users.push(find_dict(teams, $(this).val()))
          // console.log("s_users", selected_users)
          var un_select_users = [].concat.apply([], selected_users)
          // console.log('un select users', un_select_users);


        $('#id_assigned_to option').each(function () {
          if($.inArray(parseInt($(this).val()), un_select_users) != -1){
            $(this).attr('disabled', 'disabled')
            $('#id_assigned_to').select2();

          }
          else{
            $(this).show()
            $(this).removeAttr('disabled')
            $('#id_assigned_to').select2();

          }
          }
        )


          if (!selected_teams) {
            users = []
            $('#id_assigned_to option').each(function () {
            $(this).removeAttr('disabled')
            })
            $('#id_assigned_to').select2();
          } else {
            users = users.concat(_data.split(','))
          }
        });
        $('#id_teams option').each(function () {
          if ($(this).is(':selected')) {
            _data = $(this).attr('data-users').split(',')
            // console.log(' selected', $(this).attr('data-users').split(','))
            // console.log('selected', $(this).attr('data-users'))
          }
          else {
            _unselected = $(this).attr('data-users').split(',')
            // console.log('un selected', $(this).attr('data-users').split(','))
          }
        });
        // console.log('selected users teams data', users)
        var existingUsers = $('#id_assigned_to').val();
        var allUsers = users
        $('#_id_assigned_to').select2().val(allUsers).trigger('change');
        if (users.length) {

        }
      } catch (error) {
        console.log(error)
        $('#_id_assigned_to').select2().val([]).trigger('change');
      }
    })

  });

  $(document).ready(function($) {

    var teams = []
    var all_users = []
    var selected_teams = []
    var selected_users = []
    var assigned_users = []
    $.get("{% url 'leads:get_teams_and_users' %}", function(data){

          if(($('#id_teams').val()).length==0){
            $('#id_assigned_to option').each(function () {
            $(this).removeAttr('disabled')
            })
        // $('#id_assigned_to').select2().val([]).trigger('change');

          }

      teams = data['teams']
      all_users = data['users']
      try {
        var users = []
        $('#id_teams option:selected').each(function () {
          // users.push($(this).attr('data-users'))
          _data = $(this).attr('data-users');
          selected_teams.push($(this).val())
          selected_users.push(find_dict(teams, $(this).val()))
          var un_select_users = [].concat.apply([], selected_users)


        $('#id_assigned_to option').each(function () {
          if($.inArray(parseInt($(this).val()), un_select_users) != -1){
            // $(this).attr('disabled', 'disabled')
            $(this).attr('disabled', 'disabled')
            $('#id_assigned_to').select2();

          }
          else{
            $(this).show()
            $(this).removeAttr('disabled')
            $('#id_assigned_to').select2();

          }
          }
        )


          if (!selected_teams) {
            users = []
            $('#id_assigned_to option').each(function () {
            $(this).removeAttr('disabled')
            })
            $('#id_assigned_to').select2();
          } else {
            users = users.concat(_data.split(','))
          }
        });
        $('#id_teams option').each(function () {
          if ($(this).is(':selected')) {
            _data = $(this).attr('data-users').split(',')
          }
          else {
            _unselected = $(this).attr('data-users').split(',')
          }
        });
        var existingUsers = $('#id_assigned_to').val();
        // var allUsers = users.concat(existingUsers)
        var allUsers = users
        // console.log(existingUsers)
        $('#_id_assigned_to').select2().val(allUsers).trigger('change');
        if (users.length) {

        }
      } catch (error) {
        console.log(error)
        $('#_id_assigned_to').select2().val([]).trigger('change');
      }
    })

  });
</script>
{% endblock js_block %}